package org.example.printexercise;

import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {

    private List<ChatMessage> messageList;

    public ChatAdapter(List<ChatMessage> messageList) {
        this.messageList = messageList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_message, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ChatMessage message = messageList.get(position);

        if (message.getType() == ChatMessage.TYPE_OTHER) {
            holder.layoutOther.setVisibility(View.VISIBLE);
            holder.layoutMe.setVisibility(View.GONE);
            holder.tvOtherMessage.setText(message.getContent());
        } else {
            holder.layoutOther.setVisibility(View.GONE);
            holder.layoutMe.setVisibility(View.VISIBLE);

            // 对我的消息进行颜色标记
            SpannableString coloredText = createColoredText(message.getColoredContent());
            holder.tvMeMessage.setText(coloredText);
        }
    }

    private SpannableString createColoredText(String content) {
        if (content == null || content.isEmpty()) {
            return new SpannableString("");
        }

        // 直接构建显示文本
        StringBuilder displayText = new StringBuilder();
        List<int[]> errorRanges = new ArrayList<>();

        int currentPos = 0;
        while (currentPos < content.length()) {
            int redStart = content.indexOf("[RED]", currentPos);
            if (redStart == -1) {
                // 没有更多标记，添加剩余文本
                String remaining = content.substring(currentPos);
                displayText.append(remaining);
                break;
            }

            // 添加标记前的文本
            String beforeMark = content.substring(currentPos, redStart);
            displayText.append(beforeMark);
            int errorStart = displayText.length();

            // 查找标记结束位置
            int redEnd = content.indexOf("[/RED]", redStart);
            if (redEnd == -1) {
                // 没有结束标记，添加剩余文本作为错误
                String errorText = content.substring(redStart + 5);
                displayText.append(errorText);
                int errorEnd = displayText.length();
                if (errorStart < errorEnd) {
                    errorRanges.add(new int[]{errorStart, errorEnd});
                }
                break;
            }

            // 添加标记内的错误文本
            String errorText = content.substring(redStart + 5, redEnd);
            displayText.append(errorText);
            int errorEnd = displayText.length();

            if (errorStart < errorEnd) {
                errorRanges.add(new int[]{errorStart, errorEnd});
            }

            currentPos = redEnd + 6;
        }

        SpannableString spannable = new SpannableString(displayText.toString());

        // 应用红色样式
        for (int[] range : errorRanges) {
            int start = range[0];
            int end = range[1];
            if (start >= 0 && end <= spannable.length() && start < end) {
                spannable.setSpan(
                        new ForegroundColorSpan(Color.RED),
                        start, end,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                );
            }
        }

        return spannable;
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    public void addMessage(ChatMessage message) {
        messageList.add(message);
        notifyItemInserted(messageList.size() - 1);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout layoutOther, layoutMe;
        TextView tvOtherMessage, tvMeMessage;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            layoutOther = itemView.findViewById(R.id.layout_other);
            layoutMe = itemView.findViewById(R.id.layout_me);
            tvOtherMessage = itemView.findViewById(R.id.tv_other_message);
            tvMeMessage = itemView.findViewById(R.id.tv_me_message);
        }
    }
}